import sys
import time
from tkinter import messagebox

import requests

import command


def read_config():
    config = dict({})
    path = command.include_command_path("config.ini")
    with open(path, "r") as env:
        for line in env:
            find = line.find("=")
            key = line[:find - 1]
            value = line[(find + 1):]
            config[key] = value
    return config


def query_data():
    config = read_config()
    heads = {'Referer': 'https://www.bilibili.com/', 'Connection': 'close', 'User-Agent': 'Mozilla/5.0'}
    r = requests.get(config['URL'], headers=heads)
    json = r.json()
    var = json['data']['list']['vlist']
    latest = var[0]
    created = latest['created']
    bv_id = latest['bvid']
    if not check_history(bv_id):
        write_new_video(bv_id)
    else:
        sys.exit()
    title = latest['title']  # 标题
    play = latest['play']  # 播放次数
    length = latest['length']  # 时长
    time_array = time.localtime(created)
    publish_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
    show_msg(length, play, publish_time, title)


def check_history(bv_id):
    path = command.include_command_path("log\\video.txt")
    with open(path, "r") as history:
        if bv_id in history.read():
            return True
        else:
            return False


def write_new_video(bv_id):
    path = command.include_command_path("log\\video.txt")
    with open(path, "a") as history:
        history.write(bv_id)
        history.write("\n")


def show_msg(length, play, publish_time, title):
    messagebox.showinfo(title='床哥更新视频了', message=f'''
        标题：{title}
        发布时间：{publish_time}
        时长：{length}
        播放数：{play}
    ''')


if __name__ == '__main__':
    query_data()
